package de.tu_darmstadt.gdi1.battleship.model;

import java.util.Random;

import de.tu_darmstadt.gdi1.battleship.exceptions.InvalidCoordinatesException;

public class RandomMapGenerator {
	private SingleMap map = new SingleMap();;

	Random rnd = new Random();

	public SingleMap getMap() {
		return map;
	}

	public void setMap(SingleMap map) {
		this.map = map;
	}

	
	/**
	 * map with only water
	 */
	public RandomMapGenerator() {
		for (int x = 0; x < 10; x++) {
			for (int y = 0; y < 10; y++) {
				map.setEntry(x, y, new ExtendedField('-'));
			}
		}
	}


	/**
	 * places a ship randomly on a position
	 * 
	 * @param length
	 *            length of the ship
	 * @return 
	 * 		true, if operation succeeded
	 * 		
	 * @throws InvalidCoordinatesException
	 */

	public boolean placeRandomShip(int length) {
		boolean v = rnd.nextBoolean();
		map.tLockFields(length, v);

		Coordinates[] coords;
		coords = map.getUnlockedFields();
		int amoUnl = coords.length;

		// es ex. freie Felder
		if (amoUnl != 0) {
			int pos = rnd.nextInt(amoUnl);
			Coordinates start = coords[pos];

			map.placeShip(start, length, v);
			map.unlockTemp();
			return true;
		}
		map.unlockTemp();
		return false;

	}

	/**
	 * creates the whole map, uses the placeRandomShip method
	 * @return
	 * the new map
	 */
	public SingleMap createNewRandomMap() {

		boolean works = false;

		while (!works) {
			map.clear();
			map.unlockPerm();
			works = true;
			
			works = placeRandomShip(5) ? works : false;
			works = placeRandomShip(4) ? works : false;
			works = placeRandomShip(4) ? works : false;
			works = placeRandomShip(3) ? works : false;
			works = placeRandomShip(3) ? works : false;
			works = placeRandomShip(3) ? works : false;
			works = placeRandomShip(2) ? works : false;
			works = placeRandomShip(2) ? works : false;
			works = placeRandomShip(2) ? works : false;
			works = placeRandomShip(2) ? works : false;
		}
		map.unlockPerm();
		return map;
	}
}
